package com.ruoyi.business.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.ProductAttributeMapper;
import com.ruoyi.business.domain.ProductAttribute;
import com.ruoyi.business.service.IProductAttributeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品属性Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-13
 */
@Service
public class ProductAttributeServiceImpl implements IProductAttributeService {

    @Autowired
    private ProductAttributeMapper attributeMapper;

    /**
     * 查询商品属性
     * 
     * @param id 商品属性主键
     * @return 商品属性
     */
    @Override
    public ProductAttribute selectProductAttributeById(Long id)
    {
        return attributeMapper.selectProductAttributeById(id);
    }

    /**
     * 查询商品属性列表
     * 
     * @param productAttribute 商品属性
     * @return 商品属性
     */
    @Override
    public List<ProductAttribute> selectProductAttributeList(ProductAttribute productAttribute) {
        return attributeMapper.selectProductAttributeList(productAttribute);
    }


    @Override
// 为了使用 @Transactional 注解，需要导入 Spring 的事务管理相关类
    @Transactional
    public int insertProductAttribute(ProductAttribute attribute) {
        validateAttributeOptions(attribute);
        java.util.Date createTime = DateUtils.toDate(LocalDateTime.now());
        attribute.setCreateTime(createTime);
        return attributeMapper.insertProductAttribute(attribute);
    }

    @Override
    public int updateProductAttribute(ProductAttribute productAttribute) {
        validateAttributeOptions(productAttribute);
        java.util.Date updateTime = DateUtils.toDate(LocalDateTime.now());
        productAttribute.setUpdateTime(updateTime);
        return attributeMapper.updateProductAttribute(productAttribute);
    }

    @Override
    public int deleteProductAttributeByIds(Long[] ids) {
        return attributeMapper.deleteProductAttributeByIds(ids);
    }


    private void validateAttributeOptions(ProductAttribute attribute) {
        if (Arrays.asList(3, 4).contains(attribute.getType())) { // 单选/多选类型
            if (StringUtils.isEmpty(attribute.getOptions())) {
                throw new ServiceException(attribute.getName() + "必须设置选项值");
            }
            try {
                JSON.parseArray(attribute.getOptions());
            } catch (JSONException e) {
                throw new ServiceException("选项值格式错误，必须是JSON数组");
            }
        }
    }
}
